/*
 *  main.c
 *
 *  Created on: 2010-5-5
 *      Author: liuyond
 */

#include "cpu.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * load_bin_file - load a file into the pseudo random access memory
 * @path:  the file to be loaded
 * @return: return 0 if load successfully, otherwise return -1
 */
int load_bin_file(unsigned char *ram, const char *path)
{
	int  count;
	FILE *fp = NULL;
	unsigned char buf[1024];

	// open file stream
	fp = fopen(path, "rb");
	if (fp == NULL)
	{
		fprintf(stderr, "open binary file failed!\n");
		return -1;
	}
	memset(buf, 0, sizeof(buf));
	while (!feof(fp))
	{
		// read at most 1024 byte from file
		count = fread(buf, 1, sizeof(buf), fp);
		if (ferror(fp))
		{
			fprintf(stderr, "read binary file failed!\n");
			return -1;
		}
		// copy to random access memory
		memcpy(ram, buf, count);
		ram += count;
	}
	fclose(fp);
	return 0;
}

// the entry of the simulator
int main(int argc, char *argv[])
{
	cpu_t cpu;

	if (cpu_init(&cpu))
	{
		fprintf(stderr, "cpu_init failed!\n");
		exit(-1);
	}
	if (load_bin_file(cpu.ram, "d:\\Softwares\\MASM\\test.com"))
	{
		fprintf(stderr, "load_bin_file failed!\n");
		exit(-1);
	}

	cpu_loop(&cpu);

	return 0;
}
